package com.chen.session;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <b>session的跟踪</b>
 * <p>
 * 描述:<br>
 * 
 * @author 威 
 * <br>2018年5月23日 下午4:24:07 
 * @see
 * @since 1.0
 */
@WebServlet("/SessionTrack")
public class SessionTrack extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    public SessionTrack() {
        super();
    }

	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true); //不存在则新建
		Date createTime 	= new Date(session.getCreationTime());
		Date lastAccessTime = new Date(session.getLastAccessedTime());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String pageName 	= request.getServletPath();
		Integer visitCount 	= new Integer(0);
		String visitCountKey= "visitCount";
		String userIDkey 	= "userID";
		String userID 		= pageName.substring(1, pageName.length());
		if(session.isNew()){
			session.setAttribute(userIDkey, userID);
		}else {
			visitCount = (Integer) session.getAttribute(visitCountKey);
			visitCount = visitCount+1;
			userID = (String)session.getAttribute(userIDkey);
		}
		session.setAttribute(visitCountKey,  visitCount);
		System.out.println("页面名称："+pageName);
		System.out.println("创建时间："+df.format(createTime));
		System.out.println("最后访问时间："+df.format(lastAccessTime));
		System.out.println("用户ID："+userID);
		System.out.println("访问统计："+visitCount);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
